/**
 * MES System Main Application
 * Handles navigation, modal, toast notifications, and page initialization
 */

class MESApp {
    constructor() {
        this.currentPage = 'dashboard';
        this.modal = null;
        this.toast = null;
        this.apiBaseUrl = '/api';
        
        this.init();
    }

    init() {
        this.initElements();
        this.initEventListeners();
        this.updateTime();
        this.loadInitialData();
        
        // Update time every second
        setInterval(() => this.updateTime(), 1000);
    }

    initElements() {
        this.modal = document.getElementById('modal');
        this.toast = document.getElementById('toast');
        this.navItems = document.querySelectorAll('.nav-item');
        this.pages = document.querySelectorAll('.page');
    }

    initEventListeners() {
        // Navigation
        this.navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                const page = item.getAttribute('data-page');
                this.navigateToPage(page);
            });
        });

        // Modal close
        const closeBtn = document.querySelector('.close');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.closeModal());
        }

        // Close modal when clicking outside
        window.addEventListener('click', (e) => {
            if (e.target === this.modal) {
                this.closeModal();
            }
        });

        // Page-specific event listeners
        this.initProductsEventListeners();
        this.initWorkOrdersEventListeners();
        this.initProductionEventListeners();
    }

    initProductsEventListeners() {
        const addProductBtn = document.getElementById('addProductBtn');
        if (addProductBtn) {
            addProductBtn.addEventListener('click', () => this.showAddProductModal());
        }

        const productSearch = document.getElementById('productSearch');
        if (productSearch) {
            productSearch.addEventListener('input', () => this.searchProducts());
        }

        const categoryFilter = document.getElementById('categoryFilter');
        if (categoryFilter) {
            categoryFilter.addEventListener('change', () => this.filterProducts());
        }
    }

    initWorkOrdersEventListeners() {
        const addWorkOrderBtn = document.getElementById('addWorkOrderBtn');
        if (addWorkOrderBtn) {
            addWorkOrderBtn.addEventListener('click', () => this.showAddWorkOrderModal());
        }

        const statusFilter = document.getElementById('statusFilter');
        if (statusFilter) {
            statusFilter.addEventListener('change', () => this.filterWorkOrders());
        }

        const productionLineFilter = document.getElementById('productionLineFilter');
        if (productionLineFilter) {
            productionLineFilter.addEventListener('change', () => this.filterWorkOrders());
        }
    }

    initProductionEventListeners() {
        const addProductionBtn = document.getElementById('addProductionBtn');
        if (addProductionBtn) {
            addProductionBtn.addEventListener('click', () => this.showAddProductionModal());
        }

        const addRejectionBtn = document.getElementById('addRejectionBtn');
        if (addRejectionBtn) {
            addRejectionBtn.addEventListener('click', () => this.showAddRejectionModal());
        }

        const recordTypeFilter = document.getElementById('recordTypeFilter');
        if (recordTypeFilter) {
            recordTypeFilter.addEventListener('change', () => this.filterProductionRecords());
        }

        const workstationFilter = document.getElementById('workstationFilter');
        if (workstationFilter) {
            workstationFilter.addEventListener('change', () => this.filterProductionRecords());
        }
    }

    navigateToPage(page) {
        // Update active navigation item
        this.navItems.forEach(item => {
            item.classList.remove('active');
            if (item.getAttribute('data-page') === page) {
                item.classList.add('active');
            }
        });

        // Update active page
        this.pages.forEach(pageElement => {
            pageElement.classList.remove('active');
            if (pageElement.id === page) {
                pageElement.classList.add('active');
            }
        });

        this.currentPage = page;

        // Load page-specific data
        this.loadPageData(page);
    }

    loadPageData(page) {
        switch (page) {
            case 'dashboard':
                this.loadDashboardData();
                break;
            case 'products':
                this.loadProductsData();
                break;
            case 'workorders':
                this.loadWorkOrdersData();
                break;
            case 'production':
                this.loadProductionRecordsData();
                break;
        }
    }

    async loadInitialData() {
        await this.loadDashboardData();
    }

    async loadDashboardData() {
        try {
            // Load statistics
            const [products, workOrders, productionRecords] = await Promise.all([
                this.apiCall('/products'),
                this.apiCall('/workorders'),
                this.apiCall('/production-records')
            ]);

            // Update statistics
            document.getElementById('totalProducts').textContent = products.data?.length || 0;
            document.getElementById('totalWorkOrders').textContent = workOrders.data?.length || 0;
            document.getElementById('totalProductionRecords').textContent = productionRecords.data?.length || 0;
            
            // Count in-progress work orders
            const inProgressCount = workOrders.data?.filter(wo => wo.status === 'IN_PROGRESS').length || 0;
            document.getElementById('inProgressOrders').textContent = inProgressCount;

            // Load recent activities
            this.loadRecentActivities();

        } catch (error) {
            console.error('Failed to load dashboard data:', error);
            this.showToast('加载仪表盘数据失败', 'error');
        }
    }

    async loadRecentActivities() {
        const activitiesContainer = document.getElementById('recentActivities');
        try {
            // Get recent production records
            const response = await this.apiCall('/production-records');
            const records = response.data || [];
            
            // Sort by creation time and take the latest 5
            const recentRecords = records
                .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                .slice(0, 5);

            if (recentRecords.length === 0) {
                activitiesContainer.innerHTML = '<p class="no-data">暂无最近活动</p>';
                return;
            }

            const activitiesHtml = recentRecords.map(record => `
                <div class="activity-item">
                    <div class="activity-icon ${(record.recordType || '').toLowerCase()}">
                        <i class="fas ${this.getActivityIcon(record.recordType)}"></i>
                    </div>
                    <div class="activity-content">
                        <p><strong>工单 ${record.workOrder?.orderCode || record.workOrderCode || '-'}</strong> - ${record.recordType === 'PRODUCTION' ? '生产' : '不合格'}记录</p>
                        <p class="activity-meta">数量: ${record.quantity || 0} | 工作站: ${record.workstation || '-'} | ${this.formatTime(record.createTime)}</p>
                    </div>
                </div>
            `).join('');

            activitiesContainer.innerHTML = activitiesHtml;

        } catch (error) {
            console.error('Failed to load recent activities:', error);
            activitiesContainer.innerHTML = '<p class="error">加载失败</p>';
        }
    }

    getActivityIcon(recordType) {
        switch (recordType) {
            case 'PRODUCTION': return 'fa-check-circle';
            case 'REJECTION': return 'fa-exclamation-triangle';
            case 'REWORK': return 'fa-redo';
            default: return 'fa-cog';
        }
    }

    async loadProductsData() {
        const tableBody = document.getElementById('productsTableBody');
        try {
            const response = await this.apiCall('/products');
            const products = response.data || [];

            if (products.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="no-data">暂无产品数据</td></tr>';
                return;
            }

            const rowsHtml = products.map(product => `
                <tr>
                    <td>${product.productCode}</td>
                    <td>${product.productName}</td>
                    <td>${product.category}</td>
                    <td>¥${product.price}</td>
                    <td>${product.stockQuantity}</td>
                    <td>${this.formatTime(product.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editProduct(${product.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteProduct(${product.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to load products:', error);
            tableBody.innerHTML = '<tr><td colspan="7" class="error">加载失败</td></tr>';
        }
    }

    async loadWorkOrdersData() {
        const tableBody = document.getElementById('workOrdersTableBody');
        try {
            const response = await this.apiCall('/workorders');
            const workOrders = response.data || [];

            if (workOrders.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" class="no-data">暂无工单数据</td></tr>';
                return;
            }

            const rowsHtml = workOrders.map(wo => `
                <tr>
                    <td>${wo.orderCode || '-'}</td>
                    <td>${wo.product?.productName || wo.productName || '-'}</td>
                    <td>${wo.plannedQuantity || 0}</td>
                    <td>${wo.completedQuantity || 0}</td>
                    <td>${wo.rejectedQuantity || 0}</td>
                    <td><span class="status-badge ${(wo.status || '').toLowerCase()}">${this.getStatusText(wo.status)}</span></td>
                    <td>${wo.productionLine || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editWorkOrder(${wo.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteWorkOrder(${wo.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to load work orders:', error);
            tableBody.innerHTML = '<tr><td colspan="8" class="error">加载失败</td></tr>';
        }
    }

    async loadProductionRecordsData() {
        const tableBody = document.getElementById('productionRecordsTableBody');
        try {
            const response = await this.apiCall('/production-records');
            const records = response.data || [];

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="9" class="no-data">暂无生产记录</td></tr>';
                return;
            }

            const rowsHtml = records.map(record => `
                <tr>
                    <td>${record.workOrder?.orderCode || record.workOrderCode || '-'}</td>
                    <td>${record.quantity || 0}</td>
                    <td><span class="type-badge ${(record.recordType || '').toLowerCase()}">${this.getRecordTypeText(record.recordType)}</span></td>
                    <td>${record.workstation || '-'}</td>
                    <td>${record.operator || '-'}</td>
                    <td>${record.shift || '-'}</td>
                    <td><span class="quality-badge ${(record.qualityStatus || '').toLowerCase()}">${record.qualityStatus || '-'}</span></td>
                    <td>${this.formatTime(record.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editProductionRecord(${record.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteProductionRecord(${record.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to load production records:', error);
            tableBody.innerHTML = '<tr><td colspan="9" class="error">加载失败</td></tr>';
        }
    }

    getStatusText(status) {
        const statusMap = {
            'PENDING': '待处理',
            'IN_PROGRESS': '进行中',
            'COMPLETED': '已完成',
            'CANCELLED': '已取消'
        };
        return statusMap[status] || status;
    }

    getRecordTypeText(type) {
        const typeMap = {
            'PRODUCTION': '生产',
            'REJECTION': '不合格',
            'REWORK': '返工'
        };
        return typeMap[type] || type;
    }

    updateTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    formatTime(timeString) {
        if (!timeString) return '-';
        const date = new Date(timeString);
        return date.toLocaleString('zh-CN');
    }

    async apiCall(endpoint, options = {}) {
        const url = `${this.apiBaseUrl}${endpoint}`;
        const defaultOptions = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include'
        };

        try {
            const response = await fetch(url, { ...defaultOptions, ...options });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('API call failed:', error);
            throw error;
        }
    }

    showModal(title, content) {
        const modalBody = document.getElementById('modalBody');
        modalBody.innerHTML = `
            <div class="modal-header">
                <h2 class="modal-title">${title}</h2>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                ${content}
            </div>
        `;
        this.modal.style.display = 'block';
        
        // Re-attach close event listener for the new close button
        const newCloseBtn = modalBody.querySelector('.close');
        if (newCloseBtn) {
            newCloseBtn.addEventListener('click', () => this.closeModal());
        }
    }

    closeModal() {
        this.modal.style.display = 'none';
    }

    showToast(message, type = 'info') {
        this.toast.textContent = message;
        this.toast.className = `toast ${type} show`;
        
        setTimeout(() => {
            this.toast.classList.remove('show');
        }, 3000);
    }

    // Modal methods for different entities
    showAddProductModal() {
        const content = `
            <form id="productForm" class="modal-form">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">产品代码 <span class="required">*</span></label>
                        <input type="text" name="productCode" class="form-control" placeholder="请输入产品代码" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">产品名称 <span class="required">*</span></label>
                        <input type="text" name="productName" class="form-control" placeholder="请输入产品名称" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">分类 <span class="required">*</span></label>
                        <select name="category" class="form-control" required>
                            <option value="">请选择分类</option>
                            <option value="电子产品">电子产品</option>
                            <option value="电脑配件">电脑配件</option>
                            <option value="机械零件">机械零件</option>
                            <option value="原材料">原材料</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">价格 (元) <span class="required">*</span></label>
                        <input type="number" name="price" class="form-control" step="0.01" min="0" placeholder="0.00" required>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">库存数量 <span class="required">*</span></label>
                    <input type="number" name="stockQuantity" class="form-control" min="0" placeholder="请输入库存数量" required>
                </div>
                <div class="form-group">
                    <label class="form-label">产品描述</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="请输入产品描述（可选）"></textarea>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="app.closeModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" form="productForm" class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        `;
        this.showModal('添加产品', content);

        document.getElementById('productForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveProduct(new FormData(e.target));
        });
    }

    showAddWorkOrderModal() {
        const content = `
            <form id="workOrderForm">
                <div class="form-group">
                    <label>工单编码:</label>
                    <input type="text" name="workOrderCode" required>
                </div>
                <div class="form-group">
                    <label>产品名称:</label>
                    <input type="text" name="productName" required>
                </div>
                <div class="form-group">
                    <label>计划数量:</label>
                    <input type="number" name="plannedQuantity" required>
                </div>
                <div class="form-group">
                    <label>产品线:</label>
                    <select name="productionLine" required>
                        <option value="">选择产品线</option>
                        <option value="生产线A">生产线A</option>
                        <option value="生产线B">生产线B</option>
                        <option value="生产线C">生产线C</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">取消</button>
                </div>
            </form>
        `;
        this.showModal('创建工单', content);

        document.getElementById('workOrderForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveWorkOrder(new FormData(e.target));
        });
    }

    showAddProductionModal() {
        const content = `
            <form id="productionForm">
                <div class="form-group">
                    <label>工单编码:</label>
                    <input type="text" name="workOrderCode" required>
                </div>
                <div class="form-group">
                    <label>数量:</label>
                    <input type="number" name="quantity" required>
                </div>
                <div class="form-group">
                    <label>工作站:</label>
                    <select name="workstation" required>
                        <option value="">选择工作站</option>
                        <option value="工作站A1">工作站A1</option>
                        <option value="工作站B1">工作站B1</option>
                        <option value="工作站C1">工作站C1</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>操作员:</label>
                    <input type="text" name="operator" required>
                </div>
                <div class="form-group">
                    <label>班次:</label>
                    <select name="shift" required>
                        <option value="">选择班次</option>
                        <option value="早班">早班</option>
                        <option value="中班">中班</option>
                        <option value="晚班">晚班</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">取消</button>
                </div>
            </form>
        `;
        this.showModal('添加生产记录', content);

        document.getElementById('productionForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveProductionRecord(new FormData(e.target), 'PRODUCTION');
        });
    }

    showAddRejectionModal() {
        const content = `
            <form id="rejectionForm">
                <div class="form-group">
                    <label>工单编码:</label>
                    <input type="text" name="workOrderCode" required>
                </div>
                <div class="form-group">
                    <label>不合格数量:</label>
                    <input type="number" name="quantity" required>
                </div>
                <div class="form-group">
                    <label>工作站:</label>
                    <select name="workstation" required>
                        <option value="">选择工作站</option>
                        <option value="工作站A1">工作站A1</option>
                        <option value="工作站B1">工作站B1</option>
                        <option value="工作站C1">工作站C1</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>操作员:</label>
                    <input type="text" name="operator" required>
                </div>
                <div class="form-group">
                    <label>班次:</label>
                    <select name="shift" required>
                        <option value="">选择班次</option>
                        <option value="早班">早班</option>
                        <option value="中班">中班</option>
                        <option value="晚班">晚班</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">取消</button>
                </div>
            </form>
        `;
        this.showModal('添加不合格记录', content);

        document.getElementById('rejectionForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveProductionRecord(new FormData(e.target), 'REJECTION');
        });
    }

    // Save methods
    async saveProduct(formData) {
        const product = {
            productCode: formData.get('productCode'),
            productName: formData.get('productName'),
            category: formData.get('category'),
            price: parseFloat(formData.get('price')),
            stockQuantity: parseInt(formData.get('stockQuantity')),
            description: formData.get('description') || ''
        };

        try {
            await this.apiCall('/products', {
                method: 'POST',
                body: JSON.stringify(product)
            });
            
            this.showToast('产品添加成功', 'success');
            this.closeModal();
            this.loadProductsData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to save product:', error);
            this.showToast('产品添加失败', 'error');
        }
    }

    async updateProduct(formData) {
        const product = {
            id: parseInt(formData.get('id')),
            productCode: formData.get('productCode'),
            productName: formData.get('productName'),
            category: formData.get('category'),
            price: parseFloat(formData.get('price')),
            stockQuantity: parseInt(formData.get('stockQuantity')),
            description: formData.get('description') || ''
        };

        try {
            await this.apiCall(`/products/${product.id}`, {
                method: 'PUT',
                body: JSON.stringify(product)
            });
            
            this.showToast('产品更新成功', 'success');
            this.closeModal();
            this.loadProductsData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to update product:', error);
            this.showToast('产品更新失败', 'error');
        }
    }

    async saveWorkOrder(formData) {
        const workOrder = {
            orderCode: formData.get('orderCode') || formData.get('workOrderCode'),
            productName: formData.get('productName'),
            plannedQuantity: parseInt(formData.get('plannedQuantity')),
            productionLine: formData.get('productionLine'),
            status: 'PENDING',
            completedQuantity: 0,
            rejectedQuantity: 0,
            priority: formData.get('priority') || 'MEDIUM'
        };

        try {
            await this.apiCall('/workorders', {
                method: 'POST',
                body: JSON.stringify(workOrder)
            });
            
            this.showToast('工单创建成功', 'success');
            this.closeModal();
            this.loadWorkOrdersData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to save work order:', error);
            this.showToast('工单创建失败', 'error');
        }
    }

    async updateWorkOrder(formData) {
        const workOrder = {
            id: parseInt(formData.get('id')),
            orderCode: formData.get('orderCode') || formData.get('workOrderCode'),
            productName: formData.get('productName'),
            plannedQuantity: parseInt(formData.get('plannedQuantity')),
            productionLine: formData.get('productionLine'),
            status: formData.get('status'),
            priority: formData.get('priority') || 'MEDIUM'
        };

        try {
            await this.apiCall(`/workorders/${workOrder.id}`, {
                method: 'PUT',
                body: JSON.stringify(workOrder)
            });
            
            this.showToast('工单更新成功', 'success');
            this.closeModal();
            this.loadWorkOrdersData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to update work order:', error);
            this.showToast('工单更新失败', 'error');
        }
    }

    async saveProductionRecord(formData, recordType) {
        const record = {
            workOrderCode: formData.get('workOrderCode'),
            quantity: parseInt(formData.get('quantity')),
            recordType: recordType,
            workstation: formData.get('workstation'),
            operator: formData.get('operator'),
            shift: formData.get('shift'),
            qualityStatus: recordType === 'PRODUCTION' ? 'QUALIFIED' : 'UNQUALIFIED',
            remarks: formData.get('remarks') || ''
        };

        try {
            await this.apiCall('/production-records', {
                method: 'POST',
                body: JSON.stringify(record)
            });
            
            this.showToast(`${recordType === 'PRODUCTION' ? '生产' : '不合格'}记录添加成功`, 'success');
            this.closeModal();
            this.loadProductionRecordsData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to save production record:', error);
            this.showToast(`${recordType === 'PRODUCTION' ? '生产' : '不合格'}记录添加失败`, 'error');
        }
    }

    async updateProductionRecord(formData) {
        const record = {
            id: parseInt(formData.get('id')),
            workOrderCode: formData.get('workOrderCode'),
            quantity: parseInt(formData.get('quantity')),
            recordType: formData.get('recordType'),
            workstation: formData.get('workstation'),
            operator: formData.get('operator'),
            shift: formData.get('shift'),
            qualityStatus: formData.get('qualityStatus'),
            remarks: formData.get('remarks') || ''
        };

        try {
            await this.apiCall(`/production-records/${record.id}`, {
                method: 'PUT',
                body: JSON.stringify(record)
            });
            
            this.showToast('生产记录更新成功', 'success');
            this.closeModal();
            this.loadProductionRecordsData();
            this.loadDashboardData(); // Update statistics
        } catch (error) {
            console.error('Failed to update production record:', error);
            this.showToast('生产记录更新失败', 'error');
        }
    }

    // Placeholder methods for search and filter
    searchProducts() {
        const searchTerm = document.getElementById('productSearch').value.toLowerCase();
        const categoryFilter = document.getElementById('categoryFilter').value;
        
        this.filterAndDisplayProducts(searchTerm, categoryFilter);
    }

    filterProducts() {
        const searchTerm = document.getElementById('productSearch').value.toLowerCase();
        const categoryFilter = document.getElementById('categoryFilter').value;
        
        this.filterAndDisplayProducts(searchTerm, categoryFilter);
    }

    async filterAndDisplayProducts(searchTerm = '', categoryFilter = '') {
        const tableBody = document.getElementById('productsTableBody');
        try {
            const response = await this.apiCall('/products');
            let products = response.data || [];

            // Apply filters
            if (searchTerm) {
                products = products.filter(product => 
                    product.productName.toLowerCase().includes(searchTerm) ||
                    product.productCode.toLowerCase().includes(searchTerm)
                );
            }

            if (categoryFilter) {
                products = products.filter(product => product.category === categoryFilter);
            }

            if (products.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" class="no-data">没有找到符合条件的产品</td></tr>';
                return;
            }

            const rowsHtml = products.map(product => `
                <tr>
                    <td>${product.productCode}</td>
                    <td>${product.productName}</td>
                    <td>${product.category}</td>
                    <td>￥${product.price}</td>
                    <td>${product.stockQuantity}</td>
                    <td>${this.formatTime(product.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editProduct(${product.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteProduct(${product.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to filter products:', error);
            tableBody.innerHTML = '<tr><td colspan="7" class="error">过滤失败</td></tr>';
        }
    }

    filterWorkOrders() {
        const statusFilter = document.getElementById('statusFilter').value;
        const productionLineFilter = document.getElementById('productionLineFilter').value;
        
        this.filterAndDisplayWorkOrders(statusFilter, productionLineFilter);
    }

    async filterAndDisplayWorkOrders(statusFilter = '', productionLineFilter = '') {
        const tableBody = document.getElementById('workOrdersTableBody');
        try {
            const response = await this.apiCall('/workorders');
            let workOrders = response.data || [];

            // Apply filters
            if (statusFilter) {
                workOrders = workOrders.filter(wo => wo.status === statusFilter);
            }

            if (productionLineFilter) {
                workOrders = workOrders.filter(wo => wo.productionLine === productionLineFilter);
            }

            if (workOrders.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" class="no-data">没有找到符合条件的工单</td></tr>';
                return;
            }

            const rowsHtml = workOrders.map(wo => `
                <tr>
                    <td>${wo.orderCode || '-'}</td>
                    <td>${wo.product?.productName || wo.productName || '-'}</td>
                    <td>${wo.plannedQuantity || 0}</td>
                    <td>${wo.completedQuantity || 0}</td>
                    <td>${wo.rejectedQuantity || 0}</td>
                    <td><span class="status-badge ${(wo.status || '').toLowerCase()}">${this.getStatusText(wo.status)}</span></td>
                    <td>${wo.productionLine || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editWorkOrder(${wo.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteWorkOrder(${wo.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to filter work orders:', error);
            tableBody.innerHTML = '<tr><td colspan="8" class="error">过滤失败</td></tr>';
        }
    }

    filterProductionRecords() {
        const recordTypeFilter = document.getElementById('recordTypeFilter').value;
        const workstationFilter = document.getElementById('workstationFilter').value;
        
        this.filterAndDisplayProductionRecords(recordTypeFilter, workstationFilter);
    }

    async filterAndDisplayProductionRecords(recordTypeFilter = '', workstationFilter = '') {
        const tableBody = document.getElementById('productionRecordsTableBody');
        try {
            const response = await this.apiCall('/production-records');
            let records = response.data || [];

            // Apply filters
            if (recordTypeFilter) {
                records = records.filter(record => record.recordType === recordTypeFilter);
            }

            if (workstationFilter) {
                records = records.filter(record => record.workstation === workstationFilter);
            }

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="9" class="no-data">没有找到符合条件的生产记录</td></tr>';
                return;
            }

            const rowsHtml = records.map(record => `
                <tr>
                    <td>${record.workOrder?.orderCode || record.workOrderCode || '-'}</td>
                    <td>${record.quantity || 0}</td>
                    <td><span class="type-badge ${(record.recordType || '').toLowerCase()}">${this.getRecordTypeText(record.recordType)}</span></td>
                    <td>${record.workstation || '-'}</td>
                    <td>${record.operator || '-'}</td>
                    <td>${record.shift || '-'}</td>
                    <td><span class="quality-badge ${(record.qualityStatus || '').toLowerCase()}">${record.qualityStatus || '-'}</span></td>
                    <td>${this.formatTime(record.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="app.editProductionRecord(${record.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteProductionRecord(${record.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');

            tableBody.innerHTML = rowsHtml;

        } catch (error) {
            console.error('Failed to filter production records:', error);
            tableBody.innerHTML = '<tr><td colspan="9" class="error">过滤失败</td></tr>';
        }
    }

    // Placeholder methods for edit/delete operations
    async editProduct(id) {
        try {
            // First get the product data
            const response = await this.apiCall(`/products/${id}`);
            const product = response.data;
            
            if (!product) {
                this.showToast('产品不存在', 'error');
                return;
            }

            const content = `
                <form id="editProductForm" class="modal-form">
                    <input type="hidden" name="id" value="${product.id}">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">产品代码 <span class="required">*</span></label>
                            <input type="text" name="productCode" class="form-control" value="${product.productCode}" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">产品名称 <span class="required">*</span></label>
                            <input type="text" name="productName" class="form-control" value="${product.productName}" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">分类 <span class="required">*</span></label>
                            <select name="category" class="form-control" required>
                                <option value="">请选择分类</option>
                                <option value="电子产品" ${product.category === '电子产品' ? 'selected' : ''}>电子产品</option>
                                <option value="电脑配件" ${product.category === '电脑配件' ? 'selected' : ''}>电脑配件</option>
                                <option value="机械零件" ${product.category === '机械零件' ? 'selected' : ''}>机械零件</option>
                                <option value="原材料" ${product.category === '原材料' ? 'selected' : ''}>原材料</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">价格 (元) <span class="required">*</span></label>
                            <input type="number" name="price" class="form-control" step="0.01" min="0" value="${product.price}" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">库存数量 <span class="required">*</span></label>
                        <input type="number" name="stockQuantity" class="form-control" min="0" value="${product.stockQuantity}" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">产品描述</label>
                        <textarea name="description" class="form-control" rows="3">${product.description || ''}</textarea>
                    </div>
                </form>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" form="editProductForm" class="btn btn-primary">
                        <i class="fas fa-save"></i> 更新
                    </button>
                </div>
            `;
            
            this.showModal('编辑产品', content);

            document.getElementById('editProductForm').addEventListener('submit', (e) => {
                e.preventDefault();
                this.updateProduct(new FormData(e.target));
            });
            
        } catch (error) {
            console.error('Failed to load product for editing:', error);
            this.showToast('加载产品信息失败', 'error');
        }
    }

    async deleteProduct(id) {
        if (confirm('确定要删除此产品吗？此操作不可恢复。')) {
            try {
                await this.apiCall(`/products/${id}`, {
                    method: 'DELETE'
                });
                
                this.showToast('产品删除成功', 'success');
                this.loadProductsData();
                this.loadDashboardData(); // Update statistics
                
            } catch (error) {
                console.error('Failed to delete product:', error);
                this.showToast('产品删除失败', 'error');
            }
        }
    }

    async editWorkOrder(id) {
        try {
            const response = await this.apiCall(`/workorders/${id}`);
            const workOrder = response.data;
            
            if (!workOrder) {
                this.showToast('工单不存在', 'error');
                return;
            }

            const content = `
                <form id="editWorkOrderForm" class="modal-form">
                    <input type="hidden" name="id" value="${workOrder.id}">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">工单编码 <span class="required">*</span></label>
                            <input type="text" name="orderCode" class="form-control" value="${workOrder.orderCode || ''}" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">产品名称 <span class="required">*</span></label>
                            <input type="text" name="productName" class="form-control" value="${workOrder.product?.productName || workOrder.productName || ''}" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">计划数量 <span class="required">*</span></label>
                            <input type="number" name="plannedQuantity" class="form-control" value="${workOrder.plannedQuantity || 0}" min="1" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">产品线 <span class="required">*</span></label>
                            <select name="productionLine" class="form-control" required>
                                <option value="">请选择产品线</option>
                                <option value="生产线A" ${workOrder.productionLine === '生产线A' ? 'selected' : ''}>生产线A</option>
                                <option value="生产线B" ${workOrder.productionLine === '生产线B' ? 'selected' : ''}>生产线B</option>
                                <option value="生产线C" ${workOrder.productionLine === '生产线C' ? 'selected' : ''}>生产线C</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">状态</label>
                            <select name="status" class="form-control">
                                <option value="PENDING" ${workOrder.status === 'PENDING' ? 'selected' : ''}>待处理</option>
                                <option value="IN_PROGRESS" ${workOrder.status === 'IN_PROGRESS' ? 'selected' : ''}>进行中</option>
                                <option value="COMPLETED" ${workOrder.status === 'COMPLETED' ? 'selected' : ''}>已完成</option>
                                <option value="CANCELLED" ${workOrder.status === 'CANCELLED' ? 'selected' : ''}>已取消</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">优先级</label>
                            <select name="priority" class="form-control">
                                <option value="LOW" ${workOrder.priority === 'LOW' ? 'selected' : ''}>低</option>
                                <option value="MEDIUM" ${workOrder.priority === 'MEDIUM' ? 'selected' : ''}>中</option>
                                <option value="HIGH" ${workOrder.priority === 'HIGH' ? 'selected' : ''}>高</option>
                                <option value="URGENT" ${workOrder.priority === 'URGENT' ? 'selected' : ''}>紧急</option>
                            </select>
                        </div>
                    </div>
                </form>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" form="editWorkOrderForm" class="btn btn-primary">
                        <i class="fas fa-save"></i> 更新
                    </button>
                </div>
            `;
            
            this.showModal('编辑工单', content);

            document.getElementById('editWorkOrderForm').addEventListener('submit', (e) => {
                e.preventDefault();
                this.updateWorkOrder(new FormData(e.target));
            });
            
        } catch (error) {
            console.error('Failed to load work order for editing:', error);
            this.showToast('加载工单信息失败', 'error');
        }
    }

    async deleteWorkOrder(id) {
        if (confirm('确定要删除此工单吗？此操作不可恢复。')) {
            try {
                await this.apiCall(`/workorders/${id}`, {
                    method: 'DELETE'
                });
                
                this.showToast('工单删除成功', 'success');
                this.loadWorkOrdersData();
                this.loadDashboardData(); // Update statistics
                
            } catch (error) {
                console.error('Failed to delete work order:', error);
                this.showToast('工单删除失败', 'error');
            }
        }
    }

    async editProductionRecord(id) {
        try {
            const response = await this.apiCall(`/production-records/${id}`);
            const record = response.data;
            
            if (!record) {
                this.showToast('生产记录不存在', 'error');
                return;
            }

            const content = `
                <form id="editProductionRecordForm" class="modal-form">
                    <input type="hidden" name="id" value="${record.id}">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">工单编码 <span class="required">*</span></label>
                            <input type="text" name="workOrderCode" class="form-control" value="${record.workOrder?.orderCode || record.workOrderCode || ''}" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">数量 <span class="required">*</span></label>
                            <input type="number" name="quantity" class="form-control" value="${record.quantity || 0}" min="1" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">记录类型 <span class="required">*</span></label>
                            <select name="recordType" class="form-control" required>
                                <option value="PRODUCTION" ${record.recordType === 'PRODUCTION' ? 'selected' : ''}>生产</option>
                                <option value="REJECTION" ${record.recordType === 'REJECTION' ? 'selected' : ''}>不合格</option>
                                <option value="REWORK" ${record.recordType === 'REWORK' ? 'selected' : ''}>返工</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">工作站 <span class="required">*</span></label>
                            <select name="workstation" class="form-control" required>
                                <option value="">请选择工作站</option>
                                <option value="工作站A1" ${record.workstation === '工作站A1' ? 'selected' : ''}>工作站A1</option>
                                <option value="工作站B1" ${record.workstation === '工作站B1' ? 'selected' : ''}>工作站B1</option>
                                <option value="工作站C1" ${record.workstation === '工作站C1' ? 'selected' : ''}>工作站C1</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">操作员 <span class="required">*</span></label>
                            <input type="text" name="operator" class="form-control" value="${record.operator || ''}" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">班次 <span class="required">*</span></label>
                            <select name="shift" class="form-control" required>
                                <option value="">请选择班次</option>
                                <option value="早班" ${record.shift === '早班' ? 'selected' : ''}>早班</option>
                                <option value="中班" ${record.shift === '中班' ? 'selected' : ''}>中班</option>
                                <option value="晚班" ${record.shift === '晚班' ? 'selected' : ''}>晚班</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">质量状态</label>
                        <select name="qualityStatus" class="form-control">
                            <option value="QUALIFIED" ${record.qualityStatus === 'QUALIFIED' ? 'selected' : ''}>合格</option>
                            <option value="UNQUALIFIED" ${record.qualityStatus === 'UNQUALIFIED' ? 'selected' : ''}>不合格</option>
                            <option value="PENDING" ${record.qualityStatus === 'PENDING' ? 'selected' : ''}>待检验</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">备注</label>
                        <textarea name="remarks" class="form-control" rows="3" placeholder="请输入备注信息（可选）">${record.remarks || ''}</textarea>
                    </div>
                </form>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="app.closeModal()">
                        <i class="fas fa-times"></i> 取消
                    </button>
                    <button type="submit" form="editProductionRecordForm" class="btn btn-primary">
                        <i class="fas fa-save"></i> 更新
                    </button>
                </div>
            `;
            
            this.showModal('编辑生产记录', content);

            document.getElementById('editProductionRecordForm').addEventListener('submit', (e) => {
                e.preventDefault();
                this.updateProductionRecord(new FormData(e.target));
            });
            
        } catch (error) {
            console.error('Failed to load production record for editing:', error);
            this.showToast('加载生产记录信息失败', 'error');
        }
    }

    async deleteProductionRecord(id) {
        if (confirm('确定要删除此生产记录吗？此操作不可恢复。')) {
            try {
                await this.apiCall(`/production-records/${id}`, {
                    method: 'DELETE'
                });
                
                this.showToast('生产记录删除成功', 'success');
                this.loadProductionRecordsData();
                this.loadDashboardData(); // Update statistics
                
            } catch (error) {
                console.error('Failed to delete production record:', error);
                this.showToast('生产记录删除失败', 'error');
            }
        }
    }
}

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.app = new MESApp();
});